package com.example.demo.service;

import com.example.demo.common.ServerResponse;
import com.example.demo.dao.StudentRepository;
import com.example.demo.domain.Student;
import com.example.demo.enums.StudentExceptionCode;
import com.example.demo.exception.StudentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gf on 2018/10/14.
 */
@Service(value = "studentService")
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentRepository studentRepository;

    public ServerResponse<List<Student>> findByAge(Integer age) throws StudentException {
        if(age<10)
            throw  new StudentException(StudentExceptionCode.PRIMARY_SCHOOL);
        else if (age>10&&age<15)
            throw new StudentException(StudentExceptionCode.MIDDLE_SCHOOL);
        return ServerResponse.createBySuccessData(studentRepository.findByAge(age));
    }

    @Transactional
    public List<Student> insertStudent() throws Exception {
        List<Student> resultList = new ArrayList<>();

        Student student = new Student();
        student.setName("Tom");
        student.setAge(20);
        student = studentRepository.save(student);

        Student student1 = new Student();
        student1.setName("Tom");
        student1.setAge(22);
        student1 = studentRepository.save(student1);

        resultList.add(student);
        resultList.add(student1);

        return resultList;
    }
}
